<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<button id="btn1">点我发送请求</button>
	<button id="btn2">点我发送请求</button>
	<script>
		//获取按钮
		var btn = document.getElementById('btn1');
		var btn = document.getElementById('btn2');
		//为按钮添加点击事件
		btn1.onclick = function () {
			jsonp ({
				//请求地址
				url:'http://localhost:3001/better',
				data:{
					name:'lisi',
					age:30
				},
				success:function(data){
					console.log(123);
					console.log(data);
				}
			})
		  }
		btn2.onclick = function () {
			jsonp ({
				//请求地址
				url:'http://localhost:3001/better',
				success:function(data){
					console.log(456);
					console.log(data);
				}
			})
		  }
		function jsonp (options) {
			  //动态创建script标签
			  var script = document.createElement('script');
			  //拼接字符串的变量
			  var params = '';
			  for(var attr in options.data){
				params += '&' + attr +'=' + options.data[attr];
			  }
			  //创建随机函数名
			  var fnName = 'myJsonp'+Math.random().toString().replace('.','');
			  //变成全局函数
			  window[fnName] = options.success;
			  //为script标签添加src属性
			  script.src = options.url + '?callback=' + fnName + params;
			  //将script标签追加到页面中
			  document.body.appendChild(script);
			  //为script标签添加onload事件
			  script.onload = function () {
				  document.body.removeChild(script)
			    }
		}
			
		
	</script>
</body>
</html>